Home:ALL Converter>Bloc Stream Subscription Not listening to changes [Bloc to Bloc communication]

Bloc Stream Subscription Not listening to changes [Bloc to Bloc communication]

Ask Time:2022-08-14T01:25:01         Author:J.Dhinesh

Json Formatter

Here is what I'm trying to do

  1. create two blocks login bloc and authentication bloc .

  2. From authentication bloc , the login bloc has been listened and event has been added.

  3. I have tried using stream subscription and bloc listener , both failed to listen to changes from login bloc.

  4. If anymore information needed , please reply to this question .

  5. The bloc code has been added , review the code and provide suggestion on the code
    Login States

    part of 'login_bloc.dart';

    class LoginState extends Equatable { const LoginState({ this.status = FormzStatus.pure, this.username = const Username.pure(), this.password = const Password.pure(), this.userId = '', this.authenticationStatus = AuthenticationStatus.unknown, });

    final FormzStatus status;
    final Username username;
    final Password password;
    final String userId;
    final AuthenticationStatus authenticationStatus;
    LoginState copyWith(
        {FormzStatus? status,
        Username? username,
        Password? password,
        String? userId,
        AuthenticationStatus? authenticationStatus}) {
      return LoginState(
        status: status ?? this.status,
        username: username ?? this.username,
        password: password ?? this.password,
        userId: userId ?? this.userId,
        authenticationStatus: authenticationStatus ?? this.authenticationStatus,
      );
    }
    
    @override
    List<Object> get props =>
        [status, username, password, userId, authenticationStatus];
    

    }

    class LoginInitialized extends LoginState {}

Login Bloc

import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'package:formz/formz.dart';

import '../../Repositories/authentication_repository.dart';
import '../../models/password.dart';
import '../../models/username.dart';

part 'login_event.dart';
part 'login_state.dart';

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  LoginBloc({
    required AuthenticationRepository authenticationRepository,
  })  : _authenticationRepository = authenticationRepository,
        super(const LoginState()) {
    on<LoginUsernameChanged>(_onUsernameChanged);
    on<LoginPasswordChanged>(_onPasswordChanged);
    on<LoginSubmitted>(_onSubmitted);
  }

  final AuthenticationRepository _authenticationRepository;

  void _onUsernameChanged(
    LoginUsernameChanged event,
    Emitter<LoginState> emit,
  ) {
    final username = Username.dirty(event.username);
    emit(state.copyWith(
      username: username,
      status: Formz.validate([state.password, username]),
    ));
  }

  void _onPasswordChanged(
    LoginPasswordChanged event,
    Emitter<LoginState> emit,
  ) {
    final password = Password.dirty(event.password);
    emit(state.copyWith(
      password: password,
      status: Formz.validate([password, state.username]),
    ));
  }

  void _onSubmitted(
    LoginSubmitted event,
    Emitter<LoginState> emit,
  ) async {
    // emit(LoginInitialized());
    if (state.status.isValidated) {
      emit(state.copyWith(status: FormzStatus.submissionInProgress));
      try {
        var loginresult = await _authenticationRepository.LoginUser(
          state.username.value,
          state.password.value,
        );

        emit(state.copyWith(
          authenticationStatus: Au,
            status: FormzStatus.submissionSuccess,
            userId: loginresult!.data?.id.toString()));
      } catch (_) {
        emit(state.copyWith(status: FormzStatus.submissionFailure));
      }
    }
  }

  @override
  void onTransition(Transition<LoginEvent, LoginState> transition) {
    super.onTransition(transition);
    print(transition);
  }
}

I want to listen the above bloc .

Authentication Bloc

import 'dart:async';  
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../Repositories/authentication_repository.dart';
import '../../Repositories/user_repository.dart';
import '../login_bloc/login_bloc.dart';

part 'authentication_event.dart';
part 'authentication_state.dart';

class AuthenticationBloc
    extends Bloc<AuthenticationEvent, AuthenticationState> {
  AuthenticationBloc(
    this._authenticationRepository,
    this._userRepository,
    this._loginBloc,
  ) : super(const UnknownAuthenticationState(AuthenticationStatus.unknown, 0)) {
    on<AuthenticationStatusChanged>(_onAuthenticationStatusChanged);
    on<AuthenticationLogoutRequested>(_onAuthenticationLogoutRequested);

    String? userId;

    _authenticationStatusSubscription =
        _authenticationRepository.status.listen((status) {
      add(AuthenticationStatusChanged(status, userId));
    });

    loginStreamSubscription = _loginBloc.stream.listen((loginState) {
      String userId = loginState.userId;
      add(AuthenticationStatusChanged(loginState.authenticationStatus, userId));
    });
  }

  final AuthenticationRepository _authenticationRepository;
  final UserRepository _userRepository;

  late StreamSubscription<AuthenticationStatus>
      _authenticationStatusSubscription;

  final LoginBloc _loginBloc;
  late StreamSubscription<LoginState> loginStreamSubscription;

  @override
  Future<void> close() {
    _authenticationStatusSubscription.cancel();
    loginStreamSubscription.cancel();
    _authenticationRepository.dispose();
    return super.close();
  }

  void _onAuthenticationStatusChanged(
    AuthenticationStatusChanged event,
    Emitter<AuthenticationState> emit,
  ) async {
    switch (event.status) {
      case AuthenticationStatus.unauthenticated:
        return emit(const NotAuthenticatedState(
            AuthenticationStatus.unauthenticated, 0));
      case AuthenticationStatus.authenticated:
        final user = await _userRepository.tryGetUser('3');
        return emit(user != ""
            ? Authenticated(
                AuthenticationStatus.authenticated, state.userId, user)
            : const NotAuthenticatedState(
                AuthenticationStatus.unauthenticated, 0));
      default:
        return emit(
            const UnknownAuthenticationState(AuthenticationStatus.unknown, 0));
    }
  }

  void _onAuthenticationLogoutRequested(
    AuthenticationLogoutRequested event,
    Emitter<AuthenticationState> emit,
  ) {
    _authenticationRepository.logOut();
  }
}

Author:J.Dhinesh,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/73346354/bloc-stream-subscription-not-listening-to-changes-bloc-to-bloc-communication
yy